package com.csr;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ManageAgentActivity extends Activity
{
	Button btnSearch;
	Button btnBack,btnLogout;
	EditText etSearchAgent;
	HttpConn httpConn=new HttpConn();
	private ProgressDialog pd=null;
	private Handler handler=new Handler();
	UserInfo userInfo;
	MD5Generator md5Generator=new MD5Generator();
	String screen;
	short RESELLER_LEVEL=100;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manage_agent);
		Bundle extras = getIntent().getExtras();
		if(extras.containsKey("nextscreen"))
		{
			screen=extras.getString("nextscreen");
			System.out.println("Screen:"+screen);
					
			if(screen.equalsIgnoreCase("Agent"))
				RESELLER_LEVEL=1;
			else if(screen.equalsIgnoreCase("Channel Owner"))
				RESELLER_LEVEL=2;
			else if (screen.equalsIgnoreCase("Distributor")) 
				RESELLER_LEVEL=3;
		}
		btnBack=(Button)findViewById(R.id.btnPrevious);
        btnLogout=(Button)findViewById(R.id.btnLogout);
		
        btnSearch=(Button)findViewById(R.id.btnSearchAgent);
		etSearchAgent=(EditText)findViewById(R.id.etSearchAgent);
		btnBack.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
		btnLogout.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				new AlertDialog.Builder(ManageAgentActivity.this)
		        .setTitle( "Exit Application" )
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                //do stuff onclick of YES
		            	setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
						
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show();
				  		
			}
		});
		btnSearch.setOnClickListener(new OnClickListener() 
		{
			
			public void onClick(View arg0) 
			{
				if(etSearchAgent.getText().toString().trim().length()>0)
				{
					new Thread(searchAgent,"Search Agent").start();
					pd =ProgressDialog.show(ManageAgentActivity.this,    
					    	null, "Please Wait..", true);
					pd.setContentView(R.layout.progress);
				}
				else
				{
					Toast.makeText(ManageAgentActivity.this,"Please Enter Phone Number",Toast.LENGTH_SHORT).show();
				}
			 
			}
		});
		
		
		
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(requestCode==22 && resultCode==3)
		{
			setResult(2);
        	finish();
		}
			
	};
	
	Runnable searchAgent=new Runnable() 
	{ 
		public void run() 
		{
			try
			{
				  String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+
						  		  etSearchAgent.getText().toString()+"|"+AppData.getUserInfo().getpublickey()));
				  String URL=AppData.hostURL+"/WebService/iTopUp/csrapp.php/GetResellerInfo/LoginId/"+AppData.getUserInfo().getLoginID()
					  	  	+"/Phone1/"+etSearchAgent.getText().toString()+"/Checksum/"+checksum+"/format/json";
				  System.out.println("URL===>\n"+URL);
				  String response=httpConn.createHttpConn(URL);
				  System.out.println("Response:"+response);
				  final JSONObject jsonObject=new JSONObject(response);
				  
				  if(jsonObject.getString("ResponseCode").equals("000"))
	              {
					  final ResellerInfo agentInfo=new ResellerInfo();
					  
					  if(jsonObject.has("AccountName"))
						  agentInfo.setAccountName(jsonObject.getString("AccountName"));
					  
					  if(jsonObject.has("Balance"))
						  agentInfo.setBalance(""+Double.parseDouble(jsonObject.getString("Balance"))/100);
					  
					  if(jsonObject.has("ResellerLevel"))
						  agentInfo.setResellerLevel(jsonObject.getString("ResellerLevel"));
					  
					  if(jsonObject.has("IDProofType"))
						  agentInfo.setIDProofType(jsonObject.getString("IDProofType"));
					  
					  if(jsonObject.has("IDNumber"))
						  agentInfo.setIDNumber(jsonObject.getString("IDNumber"));
					  
					  if(jsonObject.has("ResellerCategory"))
						  agentInfo.setResellerCategory(jsonObject.getString("ResellerCategory"));
					  
					  if(jsonObject.has("BillingTemplate"))
						  agentInfo.setBillingTemplate(jsonObject.getString("BillingTemplate"));
					  
					  if(jsonObject.has("SaleExecutive"))
						  agentInfo.setSaleExecutive(jsonObject.getString("SaleExecutive"));
					  
					  if(jsonObject.has("DiscountMatrix"))
						  agentInfo.setDiscountMatrix(jsonObject.getString("DiscountMatrix"));
					  
					  if(jsonObject.has("Name"))
						  agentInfo.setName(jsonObject.getString("Name"));
					  
					  if(jsonObject.has("Phone1"))
						  agentInfo.setPhone1(jsonObject.getString("Phone1"));
					  
					  if(jsonObject.has("Phone2"))
						  agentInfo.setPhone2(jsonObject.getString("Phone2"));
					  
					  if(jsonObject.has("IMEI"))
						  agentInfo.setIMEI(jsonObject.getString("IMEI"));
					  
					  if(jsonObject.has("AltPhone"))
						  agentInfo.setAltPhone(jsonObject.getString("AltPhone"));
					  
					  if(jsonObject.has("Email"))
						  agentInfo.setEmail(jsonObject.getString("Email"));
					  
					  if(jsonObject.has("Address1"))
						  agentInfo.setAddress1(jsonObject.getString("Address1"));
					  
					  if(jsonObject.has("Address2"))
						  agentInfo.setAddress2(jsonObject.getString("Address2"));
					  
					  if(jsonObject.has("AreaName"))
						  agentInfo.setAreaName(jsonObject.getString("AreaName"));
					  
					  if(jsonObject.has("AreaZipCode"))
						  agentInfo.setAreaZipCode(jsonObject.getString("AreaZipCode"));
					  
					  if(jsonObject.has("State"))
						  agentInfo.setState(jsonObject.getString("State"));
					  
					  if(jsonObject.has("StateName"))
						  agentInfo.setStateName(jsonObject.getString("StateName"));
					  
					  if(jsonObject.has("MaxLevel"))
						  agentInfo.setMaxlevel(jsonObject.getString("MaxLevel"));

					 AppData.agentInfo=agentInfo;
					 
					 if(Integer.parseInt(agentInfo.getMaxlevel())==RESELLER_LEVEL)
					 {
						 //user level and searched reseller level should be same.
						 System.out.println("Search Level:"+RESELLER_LEVEL);
						 System.out.println("MAx Level:"+agentInfo.getMaxlevel());
						 if(pd.isShowing())
						 pd.dismiss();		
						 startActivityForResult(new Intent(ManageAgentActivity.this,ResellerResultTabActivity.class).putExtra("calleractivity", "manageagent"),22);	 
					 }
					 
					 else if(RESELLER_LEVEL==3&&Integer.parseInt(agentInfo.getMaxlevel())>=RESELLER_LEVEL)
					 {
						 //if distributor,then level s gretar than 3
						 System.out.println("Search Level:"+RESELLER_LEVEL);
						 System.out.println("MAx Level:"+agentInfo.getMaxlevel());
						 if(pd.isShowing())
						 pd.dismiss();
						 startActivity(new Intent(ManageAgentActivity.this,ResellerResultTabActivity.class));	 
					 }
					 else
					 {
						 handler.post(new Runnable()
		            	  {
							
							public void run() 
							{
								// TODO Auto-generated method stub
								System.out.println("Search Level:"+RESELLER_LEVEL);
								 System.out.println("MAx Level:"+agentInfo.getMaxlevel());
								pd.dismiss(); 
								Toast.makeText(ManageAgentActivity.this,"No Reseller Found",Toast.LENGTH_SHORT).show();
								 
							}
		            	  });
					 }
					  
	              }
				  else
				  {
					  handler.post(new Runnable()
	            	  {
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(ManageAgentActivity.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
	            	  });
				  }
			}
			catch(final Exception e)
			{
				handler.post(new Runnable()
          	  {
					
					public void run() 
					{
						pd.dismiss();
						Toast.makeText(ManageAgentActivity.this,"",Toast.LENGTH_SHORT).show();
					}
          	  });
				e.printStackTrace();
			}
		}
	};
}
